package com.mycinema.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.mycinema.biz.CategoryBiz;
import com.mycinema.biz.MovieBiz;
import com.mycinema.entity.Category;
import com.mycinema.entity.Movie;

@Controller
public class HomeController {

	@Autowired
	private MovieBiz movieBiz;
	@Autowired
	private CategoryBiz categoryBiz;

	@RequestMapping({ "/index", "/" })
	public String index(Model model) {
		List<Movie> list = movieBiz.getAll();
		model.addAttribute("movies", list);
		return "home-index";
	}

	@RequestMapping("/edit")
	public String details(int id, Model model) {
		Movie movie = movieBiz.fetchById(id);
		List<Category> categories = categoryBiz.getAll();
		model.addAttribute("movie", movie);
		model.addAttribute("categories", categories);
		return "movie-edit";
	}

	// 多条件组合查询+分页
	@RequestMapping("/list")
	public String list(
			@RequestParam(defaultValue = "0", required = false) int cid,
			String title,
			@RequestParam(defaultValue = "1", required = false) int page,
			Model model) {
		// 查询所有类别
		List<Category> categories = categoryBiz.getAll();
		model.addAttribute("categories", categories);
		int pageSize = 3;
		int start = (page - 1) * pageSize;
		// 查询当前页的记录
		List<Movie> movies = movieBiz.getMovies(0, cid, title, start, pageSize);
		model.addAttribute("movies", movies);
		// 总记录数
		int rows = movieBiz.fetchMovieRows(0, cid, title);
		// 总页数
		int totalPage = (int) Math.ceil((double) rows / pageSize);
		model.addAttribute("totalPages", totalPage);
		model.addAttribute("title", title);
		model.addAttribute("page", page);
		return "movie-list";
	}

}
